const express = require('express')
const crypto = require('crypto')
const moment = require('moment')
const tokenChecker = require('../util/tokenChecker')
const memberController = require('../controller/memberController')

const memberRouter = express.Router()

/* GET users listing. */
memberRouter.get('/', (req, res, next) => {
  res.send('respond user')
})

memberRouter.post('/signup', async (req, res, next) => {
  const { name, phone, recommendId, settleId, password, creditCard, creditImg, position } = req.body
  try {
    const result = await memberController.createMember({
      name,
      phone,
      recommendId,
      settleId,
      password,
      creditCard,
      creditImg,
      position
    })
    res.json({
      status: 200,
      msg: '注册成功',
      data: {
        result
      }
    })
  } catch (e) {
    // 如果error没有status字段说明是数据库抛出的错误，同一处理为服务器错误
    next(e)
  }
})

memberRouter.post('/login', async (req, res, next) => {
  const { phone, password } = req.body
  const device = req.headers['user-agent']
  const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress
  try {
    const result = await memberController.login(phone, password, device, ip)
    res.json({
      status: 200,
      msg: '登陆成功',
      data: {
        result
      }
    })
  } catch (e) {
    next(e)
  }
})
memberRouter.get('/geneChainM', tokenChecker, async (req, res, next) => {
  const { memberId } = req.params
  try {
    const a = 0
  } catch (e) {
    next(e)
  }
})
memberRouter.get('/getAll', tokenChecker, async (req, res, next) => {
  try {
    const result = await memberController.getMembers()
    res.json({
      status: 200,
      msg: '获取所有会员成功',
      data: {
        result
      }
    })
  } catch (e) {
    next(e)
  }
})
memberRouter.get('/info', tokenChecker, async (req, res, next) => {
  const memberId = req.uuId
  try {
    const info = await memberController.getMemberByKey({ memberId })
    res.json({
      status: 200,
      msg: '获取详情成功',
      data: {
        result: info
      }
    })
  } catch (e) {
    next(e)
  }
})
memberRouter.post('/logout', tokenChecker, async (req, res, next) => {
  const memberId = req.uuId
  try {
    const a = 0
  } catch (e) {
    next(e)
  }
})
module.exports = memberRouter
